<template>
  <div class="h-full w-[80%] mx-auto">
    <div class="h-[80%] flex items-center w-full">
      <ProviderSelect :items="providerList" v-model="currentModel" />
    </div>
    <div class="h-[20%] mt-4 flex items-end pb-4">
      <MessageInput @sendMessage="handleMessage" :disabled="inputDisabled" />
    </div>
  </div>
</template>

<script setup lang="ts">
  import MessageInput from '../components/MessageInput.vue'
  import ProviderSelect from '../components/ProviderSelect.vue'
  import { db } from '../db'
  import type { ProviderSelectProps } from '../type'
  import { onMounted, ref, watch } from 'vue'
  import { useRouter } from 'vue-router'
  import useConversationStore from '../store/modules/converstaionStore'
  const inputDisabled = ref(true)
  const router = useRouter()
  const conversationStore = useConversationStore()
  const providerList = ref<ProviderSelectProps[]>([])
  const currentModel = ref<string>('')
  const getProviderList = async () => {
    providerList.value = await db.providers.toArray()
  }

  watch(currentModel, val => {
    if (val) {
      inputDisabled.value = false
    } else {
      inputDisabled.value = true
    }
  })

  const handleMessage = async (message: string, base64: string, name: string) => {
    let image: string | undefined

    if (base64 && name) {
      image = await window.electronApi.copyImage({
        data: base64,
        name
      })
    }

    const [providerid, selectModel] = currentModel.value.split('/')
    const conversationid = await db.conversations.add({
      title: message,
      selectModel,
      providerid: parseInt(providerid),
      createAt: new Date().toISOString(),
      updateAt: new Date().toISOString()
    })

    conversationStore.getConversationList()

    const messageId = await db.messages.add({
      message: { role: 'user', content: message },
      type: 'question',
      conversationid,
      createAt: new Date().toISOString(),
      updateAt: new Date().toISOString(),
      ...(image ? { image } : {})
    })

    router.push({
      path: '/chat',
      query: {
        id: conversationid,
        init: messageId
      }
    })
  }

  onMounted(() => {
    getProviderList()
  })
</script>

<style scoped></style>
